/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.ui.fragment;

import android.content.Intent;
import android.os.Handler;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilDate;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.ouertech.android.agm.lib.base.utils.UtilLog;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.ouertech.android.agm.lib.ui.base.BaseUIActivity;
import com.ouertech.android.agm.lib.ui.base.BaseUIFragment;
import com.ouertech.android.agm.lib.ui.base.MenuImg;
import com.ouertech.android.agm.lib.ui.base.MenuTxt;
import com.ouertech.android.agm.lib.ui.base.UIOptions;
import com.ouertech.android.agm.lib.ui.base.defaults.fragment.BaseSystemFragment;
import com.ouertech.android.agm.lib.ui.base.defaults.fragment.BaseTopFragment;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.Follow;
import com.simon.mengkou.data.bean.base.Image;
import com.simon.mengkou.data.bean.base.SignResult;
import com.simon.mengkou.data.bean.base.User;
import com.simon.mengkou.data.cache.DataCacheImpl;
import com.simon.mengkou.data.enums.EDirection;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.adapter.CommonFollowAdapter;
import com.simon.mengkou.ui.adapter.UserImageAdapter;
import com.simon.mengkou.ui.adapter.UserShareOrderAdapter;
import com.simon.mengkou.ui.dialog.SignDialog;
import com.simon.mengkou.ui.view.AvatarSimpleDraweeView;
import com.simon.mengkou.utils.UtilOuer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/2/29.
 * desc    : 首页
 */
public class UserFragment extends BaseUIFragment
        implements PullToRefreshBase.OnRefreshListener2<ListView> {
    //头像
    AvatarSimpleDraweeView mSdvAvatar;
    //昵称
    @Bind(R.id.base_id_appbar_toolbar_title)
    TextView mTvNick;
    //积分
    TextView mTvScore;
    //关注
    TextView mTvFollow;
    //粉丝
    TextView mTvFans;
    //话题
    TextView mTvTopic;

    @Bind(R.id.common_pulltorefresh_id_list)
    PullToRefreshListView mPtrView;

    private UserImageAdapter mAdapter;
    private String mMaxId = CstOuer.PAGE.DEFAULT_MAXID;

    @Override
    protected long initOptions() {
        return UIOptions.UI_OPTIONS_SYSTEMBAR
                | UIOptions.UI_OPTIONS_APPBAR_CUSTIOM
                | UIOptions.UI_OPTIONS_CONTENT_CUSTOM;
    }


    @Override
    protected void initAppCustom() {
        setAppCustomLayout(R.layout.layout_user_header);
    }


    @Override
    protected void initLayout() {
        setContentView(R.layout.layout_common_pulltorefresh_list);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this, getView());

        View header = LayoutInflater.from(mActivity).inflate(R.layout.layout_user_info, null);
        mPtrView.getRefreshableView().addHeaderView(header);

        //头像
        mSdvAvatar = (AvatarSimpleDraweeView) header.findViewById(R.id.user_id_avatar);
        mSdvAvatar.loadAvatar(OuerApplication.mUser.getAvatarUrl(), OuerApplication.mUser.getLevel());
        mSdvAvatar.setOnClickListener(this);

        //昵称
        if(UtilString.isNotBlank(OuerApplication.mUser.getNick())) {
            mTvNick.setText(OuerApplication.mUser.getNick());
        } else {
            mTvNick.setText(OuerApplication.mUser.getPhone());
        }

        //积分
        mTvScore = (TextView) header.findViewById(R.id.user_id_score);
        mTvScore.setText(getString(R.string.user_score, OuerApplication.mUser.getIntegral()));
        mTvScore.setOnClickListener(this);

        //关注
        mTvFollow = (TextView) header.findViewById(R.id.user_id_follow);
        mTvFollow.setText(Html.fromHtml(getString(R.string.user_follow, OuerApplication.mUser.getFollowCount())));
        mTvFollow.setOnClickListener(this);

        //粉丝
        mTvFans = (TextView) header.findViewById(R.id.user_id_fans);
        mTvFans.setText(Html.fromHtml(getString(R.string.user_fans, OuerApplication.mUser.getFansCount())));
        mTvFans.setOnClickListener(this);

        //收藏
        mTvTopic = (TextView) header.findViewById(R.id.user_id_topic);
        mTvTopic.setText(Html.fromHtml(getString(R.string.user_topic, OuerApplication.mUser.getTopicNum())));
        mTvTopic.setOnClickListener(this);

        //购物车
        findViewById(R.id.user_id_cart).setOnClickListener(this);
        //订单
        findViewById(R.id.user_id_order).setOnClickListener(this);
        //优惠券
        findViewById(R.id.user_id_coupon).setOnClickListener(this);
        //心愿单
        findViewById(R.id.user_id_tuan).setOnClickListener(this);


        mPtrView.setOnRefreshListener(this);
        mPtrView.setMode(PullToRefreshBase.Mode.DISABLED);

        mAdapter = new UserImageAdapter(mActivity);
        mPtrView.setAdapter(mAdapter);

        //获取缓存
        List<Follow> datas = OuerApplication.mCacheFactory.getCache(DataCacheImpl.UserFollowCache.class,
                OuerApplication.mUser.getUserId())
                .getData();

        if(UtilList.isNotEmpty(datas)) {
            mAdapter.setList(datas);
            mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        getData(CstOuer.PAGE.DEFAULT_MAXID, EDirection.REFRESH);



        registerAction(CstOuer.BROADCAST_ACTION.USER_MODIFY_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.FOLLOW_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.TOPIC_FOLLOW_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.SHARE_ORDER_ADD_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.USER_SIGN_ACTION);
    }

    @Override
    protected void onReceive(Intent intent) {
        super.onReceive(intent);
        String action = intent.getAction();

        //更新用户信息
        if(CstOuer.BROADCAST_ACTION.USER_MODIFY_ACTION.equals(action)) {
            mSdvAvatar.loadAvatar(OuerApplication.mUser.getAvatarUrl(), OuerApplication.mUser.getLevel());

            if(UtilString.isNotBlank(OuerApplication.mUser.getNick())) {
                mTvNick.setText(OuerApplication.mUser.getNick());
            } else {
                mTvNick.setText(OuerApplication.mUser.getPhone());
            }
        } else if(CstOuer.BROADCAST_ACTION.FOLLOW_ACTION.equals(action)) {
            mTvFollow.setText(Html.fromHtml(getString(R.string.user_follow, OuerApplication.mUser.getFollowCount())));
        } else if(CstOuer.BROADCAST_ACTION.TOPIC_FOLLOW_ACTION.equals(action)) {
            mTvTopic.setText(Html.fromHtml(getString(R.string.user_topic, OuerApplication.mUser.getTopicNum())));
        } else if(CstOuer.BROADCAST_ACTION.SHARE_ORDER_ADD_ACTION.equals(action)) {
            getData(CstOuer.PAGE.DEFAULT_MAXID, EDirection.REFRESH);
        } else if(CstOuer.BROADCAST_ACTION.USER_SIGN_ACTION.equals(action)) {
            mTvScore.setText(getString(R.string.user_score, OuerApplication.mUser.getIntegral()));
        }
    }


    /**
     * 设置
     */
    @OnClick(R.id.user_id_setting)
    public void presentSetting() {
        OuerDispatcher.presentSettingActivity(mActivity);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.user_id_score://积分
                presentScore();
                break;
            case R.id.user_id_cart://购物车
                presentCart();
                break;
            case R.id.user_id_order://订单
                presentOrder();
                break;
            case R.id.user_id_coupon://优惠券
                presentCoupon();
                break;
            case R.id.user_id_tuan://心愿单
                presentGroup();
                break;
            case R.id.user_id_avatar://编辑个人信息
                presentUserModify();
                break;
            case R.id.user_id_fans://粉丝
                presentUserFans();
                break;
            case R.id.user_id_follow://关注
                presentUserFollow();
                break;
            case R.id.user_id_topic://收藏
                presentUserTopic();
                break;

        }
    }

    /**
     * 积分说明
     */
    public void presentScore() {
        OuerDispatcher.presentScoreActivity(mActivity);
    }

    /**
     * 修改用户信息
     */
    public void presentUserModify() {
        OuerDispatcher.presentUserModifyActivity(mActivity);
    }

    /**
     * 购物车
     */
    public void presentCart() {
        OuerDispatcher.presentCartActivity(mActivity);
    }

    /**
     * 订单
     */
    public void presentOrder() {
        OuerDispatcher.presentOrderActivity(mActivity);
    }

    /**
     * 优惠券
     */
    public void presentCoupon() {
        OuerDispatcher.presentCouponActivity(mActivity);
    }

    /**
     * 心愿单
     */
    public void presentGroup() {
        OuerDispatcher.presentWishListActivity(mActivity);
    }

    /**
     * 打开我的关注
     */
    public void presentUserFollow() {
        OuerDispatcher.presentFollowActivity(mActivity, OuerApplication.mUser.getUserId());
    }

    /**
     * 打开我的粉丝
     */
    public void presentUserFans() {
        OuerDispatcher.presentFanActivity(mActivity, OuerApplication.mUser.getUserId());
    }

    /**
     * 打开我的收藏
     */
    public void presentUserTopic() {
        OuerDispatcher.presentUserCollectionActivity(mActivity);
    }



    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        //下拉刷新
        getData(CstOuer.PAGE.DEFAULT_MAXID, EDirection.REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        //上拉加载更多
        getData(mMaxId, EDirection.LOADMORE);
    }

    /**
     * 获取用户晒单
     * @param maxId
     * @param direction
     */
    private void getData(final String maxId, final int direction) {
        AgnettyFuture future = OuerApplication.mOuerFuture.userShareOrder(
                maxId, CstOuer.PAGE.DEFAULT_MINID,  CstOuer.PAGE.DEFAULT_SIZE,
                OuerApplication.mUser.getUserId(),
                new OuerFutureListener(mActivity){

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        mPtrView.onRefreshComplete();
                        List<Follow> datas = (List<Follow>) result.getAttach();

                        if(direction == EDirection.REFRESH) {
                            OuerApplication.mCacheFactory.getCache(DataCacheImpl.UserFollowCache.class,
                                    OuerApplication.mUser.getUserId())
                                    .save(datas);

                            int count = UtilList.getCount(datas);
                            //设置最新的max id
                            if(count != 0) {
                                mMaxId = datas.get(count - 1).getId();
                            }

                            if(count < CstOuer.PAGE.DEFAULT_SIZE) {
                                mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            } else {
                                mPtrView.setMode(PullToRefreshBase.Mode.BOTH);
                            }

                            mAdapter.setList(datas);
                        } else {
                            int count = UtilList.getCount(datas);
                            //设置最新的max id
                            if(count != 0) {
                                mMaxId = datas.get(count - 1).getId();
                            }

                            //数据已读取完
                            if(count < CstOuer.PAGE.DEFAULT_SIZE) {
                                mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            }

                            mAdapter.addList(datas);
                        }
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        mPtrView.onRefreshComplete();
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        mPtrView.onRefreshComplete();
                    }
                });

        attachDestroyFutures(future);
    }




}
